#pragma once
#include <iostream>
#include <pthread.h>


namespace LockModule
{
    class Mutex
    {
    public:
        //锁是不允许被赋值和拷贝的 一把锁只能存在一个
        Mutex(const Mutex&) = delete;
        const Mutex& operator = (const Mutex&) = delete;
        //初始化锁
        Mutex()
        {
          int n = pthread_mutex_init(&_lock,nullptr);
          if(n!=0)
          {
            std::cout<<"锁初始化失败"<<std::endl;
          }
        }
        //销毁锁
        ~Mutex()
        {
          int n = pthread_mutex_destroy(&_lock);
          if(n!=0)
          {
            std::cout<<"锁销毁化失败"<<std::endl;
          }
        }
        //加锁
        void Lock()
        {
           int n = pthread_mutex_lock(&_lock);
           if(n!=0)
           {
             std::cout<<"加锁失败"<<std::endl;
           }
        }
        //解锁
        void Unlock()
        {
          int n = pthread_mutex_unlock(&_lock);
          if(n!=0)
          {
            std::cout<<"解锁失败"<<std::endl;
          }
        }
        pthread_mutex_t *LockPtr()
        {
            return &_lock;
        }

    private:
        pthread_mutex_t _lock;
    };
    //一个小tips可以在代码块内做到自动加锁和解锁不用手动去操作
    class LockGuard
    {
    public:
        LockGuard(Mutex &mtx):_mtx(mtx)
        {
            _mtx.Lock();
        }
        ~LockGuard()
        {
            _mtx.Unlock();
        }
    private:
        Mutex &_mtx;
    };
}
